<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/index.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css"> <!-- Font Awesome -->
    <title>{{.title}}</title>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            var modal = document.getElementById("deleteModal");
            var closeModal = document.getElementsByClassName("close")[0];
            var confirmDeleteBtn = document.getElementById("confirmDelete");
            var cancelBtn = document.getElementsByClassName("cancel")[0];
            var modalMessage = document.getElementById("modalMessage");
            var currentRow = null;

            function openModal(message, showCancel = true) {
                modalMessage.textContent = message;
                modal.style.display = "block";
                if (!showCancel) {
                    cancelBtn.style.display = "none";
                } else {
                    cancelBtn.style.display = "inline-block";
                }
                confirmDeleteBtn.onclick = function() {
                    closeModalFunction();
                };
            }

            function shareStudent(student) {
            const shareUrl = `${window.location.origin}/share?name=${encodeURIComponent(student.name)}&chinese=${student.chinese}&math=${student.math}&english=${student.english}`;
            navigator.clipboard.writeText(shareUrl).then(() => {
                fetch('/share', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(student)
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    openModal("分享链接已复制", false);
                })
                .catch(error => {
                    console.error('分享链接复制或数据库记录失败:', error);
                    openModal("分享失败，请重试！");
                });
                }).catch(error => {
                    console.error('复制到剪贴板失败:', error);
                    openModal("分享失败，请重试！");
                });
            }

            document.querySelectorAll('.share-button').forEach(button => {
                button.addEventListener('click', function(event) {
                    event.preventDefault();
                    var row = button.parentElement.parentElement;
                    var student = {
                        name: row.querySelector('.student-name').innerText,
                        chinese: parseInt(row.querySelector('.student-chinese').innerText),
                        math: parseInt(row.querySelector('.student-math').innerText),
                        english: parseInt(row.querySelector('.student-english').innerText)
                    };
                    shareStudent(student);
                });
            });

            function closeModalFunction() {
                modal.style.display = "none";
                confirmDeleteBtn.onclick = null;
            }

            function deleteStudent(studentId, row) {
                fetch('/delete_one_row', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ Id: studentId }),
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    row.remove();
                    openModal("学生已成功删除！", false);
                    confirmDeleteBtn.onclick = function() {
                        closeModalFunction();
                        location.reload(); // 添加这一行来刷新页面
                    };
                })
                .catch(error => {
                    console.error('请求过程中出现问题:', error);
                    openModal("删除失败，请重试！");
                });
            }

            function favoriteStudent(student, button) {
                fetch('/favorite/add', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(student),
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    openModal("学生已成功收藏！", false);
                    button.querySelector('i').classList.add('favorited'); // 收藏成功后更改图标颜色
                    confirmDeleteBtn.onclick = function() {
                        closeModalFunction();
                    };
                })
                .catch(error => {
                    console.error('请求过程中出现问题:', error);
                    openModal("收藏失败，学生信息已存在！");
                });
            }

            document.querySelectorAll('.favorite-button').forEach(button => {
                button.addEventListener('click', function(event) {
                    event.preventDefault();
                    var row = button.parentElement.parentElement;
                    var student = {
                        id: parseInt(row.dataset.studentId),
                        name: row.querySelector('.student-name').innerText,
                        chinese: parseInt(row.querySelector('.student-chinese').innerText),
                        math: parseInt(row.querySelector('.student-math').innerText),
                        english: parseInt(row.querySelector('.student-english').innerText)
                    };
                    favoriteStudent(student, button);
                });
            });

            var deleteButtons = document.querySelectorAll('.delete-button');
            deleteButtons.forEach(button => {
                button.addEventListener('click', function(event) {
                    event.preventDefault();
                    currentRow = button.parentElement.parentElement;
                    var studentId = parseInt(currentRow.dataset.studentId);

                    openModal("确认删除该学生吗？");

                    confirmDeleteBtn.onclick = function() {
                        deleteStudent(studentId, currentRow);
                    };
                });
            });

            closeModal.onclick = function() {
                closeModalFunction();
            };

            cancelBtn.onclick = function() {
                closeModalFunction();
            };

            window.onclick = function(event) {
                if (event.target == modal) {
                    closeModalFunction();
                }
            };
            function handleFormSubmit(event) {
                event.preventDefault(); // 阻止表单默认提交

                var searchID = document.getElementById("search").value;
                var errorMessage = document.getElementById("error-message");

                // 清除之前的错误消息
                errorMessage.innerText = "";

                // 创建XMLHttpRequest对象
                var xhr = new XMLHttpRequest();
                xhr.open("GET", "/search?id=" + encodeURIComponent(searchID), true);

                // 处理响应
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4) {
                        if (xhr.status === 200) {
                            try {
                                var student = JSON.parse(xhr.responseText);
                                // 将学生信息存储到localStorage
                                localStorage.setItem('student', JSON.stringify(student));
                                // 跳转到新的HTML页面
                                window.location.href = '/search.html';
                            } catch (error) {
                                console.error('解析JSON时出错:', error);
                                errorMessage.innerText = "查询失败，请重试";
                                errorMessage.classList.add('error-message');
                            }
                        } else if (xhr.status === 404) {
                            errorMessage.innerText = "没有找到学生信息，请重新输入！";
                            errorMessage.classList.add('error-message');
                        } else {
                            errorMessage.innerText = "查询失败，请重试";
                            errorMessage.classList.add('error-message');
                        }
                    }
                };

                // 发送请求
                xhr.send();
            }

            document.getElementById("searchForm").addEventListener("submit", handleFormSubmit);

        });
    </script>
</head>
<body class="container">
<header>
    <h1 class="title">{{.title}}</h1>
</header>
<main>
    <section class="students-table">
        <table>
            <thead>
            <tr>
                <th>序号</th>
                <th>学号</th>
                <th>姓名</th>
                <th>语文</th>
                <th>数学</th>
                <th>英语</th>
                <th colspan="3">操作</th>
            </tr>
            </thead>
            <tbody>
            {{range $index, $value := .student_slice}}
            <tr data-student-id="{{$value.Id}}">
                <td>{{inc $index}}</td>
                <td class="student-id">{{$value.Id}}</td>
                <td class="student-name">{{$value.Name}}</td>
                <td class="student-chinese">{{$value.Chinese}}</td>
                <td class="student-math">{{$value.Math}}</td>
                <td class="student-english">{{$value.English}}</td>
                <td>
                    <a class="edit-link" href="/edit?id={{$value.Id}}" title="编辑">
                        <i class="fas fa-edit"></i> <!-- 编辑图标 -->
                    </a>
                </td>
                <td>
                    <button class="delete-button" title="删除">
                        <i class="fas fa-trash-alt"></i> <!-- 垃圾桶图标 -->
                    </button>
                </td>
                <td>
                    <button class="favorite-button" title="收藏">
                        <i class="fas fa-star"></i> <!-- 五角星图标 -->
                    </button>
                    <button class="share-button" title="分享">
                        <i class="fas fa-share"></i> <!-- 分享图标 -->
                    </button>
                </td>
            </tr>
            {{end}}
            </tbody>
        </table>
    </section>
    <div class="actions">
        <a href="http://localhost:8080/add">添加学生</a>
        <a href="http://localhost:8080/favorite">我的收藏</a>
        <a href="http://localhost:8080/share_list">我的分享</a> 
        <a href="http://localhost:8080/recycle_bin">回收站</a> 
    </div>
    
    <div class="search-form">
        <form id="searchForm" action="/search" method="get" onsubmit="return handleFormSubmit(event)">
            <label for="search">请输入学生学号:</label>
            <input type="text" id="search" name="id">
            <button type="submit">确认</button>
        </form>
    </div>

    <div id="error-message" class="error-message"></div>
    <div id="deleteModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <span class="close">&times;</span>
            </div>
            <div class="modal-body">
                <p id="modalMessage"></p>
            </div>
            <div class="modal-footer">
                <button class="cancel">取消</button>
                <button class="confirm" id="confirmDelete">确认</button>
            </div>
        </div>
    </div>
</main>
</body>
</html>
